<?php

/**
 * 公众号图文评论
 * Class NewsCommentAction
 * @author jie 20170921
 */
class NewsCommentAction extends Action
{
    /**
     * 查看指定文章的评论数据
     * @param $mediaId /自媒体id
     * @param $type /是否精选 0普通/1精选
     * @return object
     */
    public function listComment($mediaId, $type=0){

        /*3.查看指定文章的评论数据
	https://api.weixin.qq.com/cgi-bin/comment/list?access_token=ACCESS_TOKEN
		--	param{
		--			“msg_data_id” : MSG_DATA_ID,	群发消息id
		--			“index” : INDEX,				图文索引
		--			“begin”: BEGIN,					起始位置
		--			“begin”: BEGIN,					起始位置
		--			“begin”: BEGIN,					起始位置
		--			“count”: COUNT,					获取数量<=50
		--			“type” : TYPE					精选/普通
		--		}*/
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $cid = Session::$user['customerId'];
        //查询出所有的图文索引数据得到索引ind以及msg_data_id以及count
        Session::switchCustomer(0);
        $newsInd_table = M('news_index_comment');
        $newsIndDet_table = M('news_comment_detail');
        Session::switchCustomer($cid);

        //查询发送成功的图文
        $newsIndArr = $newsInd_table->where(['cid'=>$cid, 'mediaId'=>$mediaId, 'status'=>'success'])
            ->field('id,msg_data_id,news_index,comment_total')->select();
        if($newsIndArr == null){
            Log::write('jie--new-1220'.$newsInd_table->getLastSql());
            Output::instance()->object([
                'code'=>-1,
                'msg'=>'暂未发表图文'
            ]);
            return;
        }

        $access_token = WeixinApi::getAccessToken(true, null, null, $mediaId);
        if(!$access_token){
            Output::instance()->object([
                'code'=>-1,
                'msg'=>'access_token不存在'
            ]);
            return;
        }
        $comData = [];
        for($i=0;$i<count($newsIndArr);$i++){
            /*每循环一次获取一条图文的全部评论从最新留言往历史留言拉取*/
            $maxCommentId = $newsIndDet_table->where(['news_ind_id'=>$newsIndArr[$i]['id'],
                'cid'=>$cid])->order('user_comment_id desc')->getField('max(user_comment_id)');
            $comDatas = WxNewsComment::getCommentList($mediaId,$newsIndArr[$i]['msg_data_id'],$newsIndArr[$i]['news_index'],$maxCommentId,$type);
            if($comDatas == null){
                continue;
            }
            $sql = 'INSERT INTO `wx_news_comment_detail`
(`cid`,`mediaId`, `news_ind_id`,`news_index`, `comment_content`, `openid`, `user_comment_id`, `comment_time`, `comment_type`, `comment_reply`, `createTime`) VALUES ';
            foreach($comDatas as $k=>$v){
                /*var_dump($newsIndDet_table->getLastSql());
                var_dump($comDatas);
                var_dump($maxCommentId);*/
                if($v['user_comment_id'] <= intval($maxCommentId)){
                    break;
                }
                if(!$v['reply']){
                    $reply = '';
                }else{
                    $reply = json_encode($v['reply']);
                }
                $sql .= "('".$cid."','".$mediaId."', '".$newsIndArr[$i]['id']."', '".$newsIndArr[$i]['news_index']."', '".$v['content']."', '".$v['openid']."','".$v['user_comment_id']."','".date('Y-m-d H:i:s', $v['create_time'])."','".$v['comment_type']."','".$reply."','".date('Y-m-d H:i:s')."'),";
            }
            $sql = trim($sql, ',').';';
            $addRet = M()->query($sql);
            //var_dump(M()->getLastSql());
            if(!$addRet){
                Log::write('拉取留言保存失败'.M()->getLastSql());
            }

            //更索引表的total,由于total拉取回来的非总数,需要单独计算
            /*$totalRet = $newsInd_table->where(['id'=>$newsIndArr[$i]['id']])->save([
                'comment_total'=>$total
            ]);*/
        }
        Output::instance()->resultCode();
    }

    /**
     * 获取图文评论
     * @param $mediaId /自媒体id
     * @param $search /关键词搜索 留言内容昵称
     * @param $start /分页起始
     * @param $limit /分页大小
     * @param $orderBy  /排序     time时间排序/total留言总数/electTotal精选留言总数
     * @param $timeSearch /时间搜索 0不限/1今天/2昨天/3前天/4最近5天
     * @return object
     */
    public function getComment($mediaId, $search='', $start=0, $limit=10, $orderBy='time',$timeSearch=''){
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        //按照评论时间倒序查,同时查询出用户的图像昵称
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $newsCom_table = M('news_comment_detail');
        Session::switchCustomer($cid);

        $map = [];
        $map['a.cid'] = $cid;
        $map['a.deleted'] = 0;
        if($search){
            $map['a.comment_content|u.nickname'] = [["like",'%'.$search.'%'],'or'];
        }

        if($orderBy == 'time' || empty($orderBy)){
            $order = 'comment_time desc';
        }else if($orderBy == 'total'){
            $order='total desc';
        }else if($orderBy == 'electTotal'){
            $order = 'electTotal desc';
        }

        switch($timeSearch){
            case 1://今天
                $startTime = date('Y-m-d 00:00:00');
                $endTime = date("Y-m-d H:i:s");
                $map['a.comment_time'] = [['egt',$startTime],['elt',$endTime]];
                break;
            case 2://昨天
                $startTime = date("Y-m-d 00:00:00", strtotime("-1 day"));
                $endTime = date('Y-m-d 00:00:00');
                $map['a.comment_time'] = [['egt',$startTime],['elt',$endTime]];
                break;
            case 3://前天
                $startTime = date("Y-m-d 00:00:00", strtotime("-2 day"));
                $endTime = date("Y-m-d 00:00:00", strtotime("-1 day"));
                $map['a.comment_time'] = [['egt',$startTime],['elt',$endTime]];
                break;
            case 4://最近5天
                $startTime = date("Y-m-d 00:00:00", strtotime("-4 day"));
                $endTime = date("Y-m-d H:i:s");
                $map['a.comment_time'] = [['egt',$startTime],['elt',$endTime]];
                break;
        }
        $commentList = $newsCom_table->alias('a')
            ->join('inner join wx_'.$cid.'_user_weixin_info u on a.openid=u.openid')
            ->join('inner join wx_news_index_comment i on a.news_ind_id=i.id and i.mediaId='.$mediaId)
            ->join('inner join wx_'.$cid.'_material m on i.materialId=m.id')
            ->where($map)
            ->order($order)
            ->limit($start, $limit)
            ->field('u.nickname,u.headimgurl,a.id,a.news_ind_id as newsIndId,a.comment_content as content,a.openid,
a.user_comment_id as commentId,a.comment_time as commentTime,a.comment_type as commentType,a.comment_reply as commentReply,
i.msg_data_id as msgDataId,i.news_index as idx,i.materialId,m.xml')
            ->select();
        Log::write('jie----1223'.$newsCom_table->getLastSql());
        /*if(!empty($search)){
            $searchWhere = 'AND ( ((a.comment_content LIKE %'.$search.'%)) OR ((u.nickname LIKE %'.$search.'%)) )';
        }
        $sql = 'SELECT u.nickname,u.headimgurl,a.id,a.news_ind_id as newsIndId,a.comment_content as content,a.openid,
a.user_comment_id as commentId,a.comment_time as commentTime,a.comment_type as commentType,a.comment_reply as commentReply,
i.msg_data_id as msgDataId,i.news_index as idx,i.materialId,m.xml FROM wx_news_comment_detail a inner join
 wx_'.$cid.'_user_weixin_info u on a.openid=u.openid inner join wx_news_index_comment i on a.news_ind_id=i.id and i.mediaId='.$mediaId.'
 inner join wx_'.$cid.'_material m on i.materialId=m.id WHERE ( a.cid = '.$cid.' ) AND ( a.deleted = 0 )
 '.$searchWhere.' ORDER BY a.comment_time desc LIMIT '.$start.','.$limit;
        $commentList = M()->query($sql);*/
        $total = $newsCom_table->alias('a')
            ->field('a.id')
            ->join('inner join wx_'.$cid.'_user_weixin_info u on a.openid=u.openid')
            ->join('inner join wx_news_index_comment i on a.news_ind_id=i.id and i.mediaId='.$mediaId)
            ->join('inner join wx_'.$cid.'_material m on i.materialId=m.id')
            ->where($map)
            ->count();

        if($commentList == null){
            Log::write('jie---1221-'.$newsCom_table->getLastSql());
            Output::instance()->object([
                'code'=>-1,
                'msg'=>'暂无留言'
            ]);
            return;
        }

        //获取到图文id以及索引, 取到图文标题
        $newsComArr = [];
        foreach($commentList as $k=>$v){
            $news = simplexml_load_string($v['xml'], 'SimpleXMLElement', LIBXML_NOCDATA);
            $news = json_decode(json_encode($news), true);
            if(!empty($news['Articles']['item'][0])){
                $v['newsTitle'] = $news['Articles']['item'][$v['idx']]['title'];    //多图文
            }else{
                $v['newsTitle'] = $news['Articles']['item']['title'];   //单图文
            }
            unset($v['xml']);
            if($v['commentReply']){
                $v['commentReply'] = json_decode($v['commentReply'], true);
            }
            $newsComArr[$k] = $v;
        }

        Output::instance()->objArray($newsComArr, $total);

    }

    /**
     * 获取图文列表
     * @param $mediaId /自媒体id
     * @param $start /分页开始
     * @param $limit /分页大小
     * @param $order /排序规则
     * @param $by /排序字段
     */
    public function getNewsList($mediaId, $start=0, $limit=10, $order='desc', $by='createTime'){
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $newsInd_table = M('news_index_comment');
        $newsIndDef_table = M('news_comment_detail');
        Session::switchCustomer($cid);

        $map = [];
        $map['a.cid'] = $cid;
        $map['a.mediaId'] = $mediaId;
        $map['a.status'] = 'success';
        $newsList = $newsInd_table->alias('a')
            ->join('inner join wx_'.$cid.'_material b on a.materialId=b.id')
            ->where($map)
            ->field('a.*,b.xml')
            ->limit($start, $limit)
            ->order([$by=>$order])
            ->select();
        Log::write('jie--newList'.$newsInd_table->getLastSql());
        $total = $newsInd_table->alias('a')
            ->join('inner join wx_'.$cid.'_material b on a.materialId=b.id')
            ->where($map)
            ->count();
        if(!$newsList){
            Output::instance()->object([
                'code'=>-1,
                'msg'=>'暂无图文'
            ]);
            return;
        }

        $newsArr = [];
        foreach($newsList as $k=>$v){
            $oneNewTotal = $newsIndDef_table->where(['cid'=>$cid,'mediaId'=>$mediaId,'news_ind_id'=>$v['id'],
                'news_index'=>$v['news_index'],'deleted'=>0])->count();
            $v['comment_total'] = $oneNewTotal;
            $news = simplexml_load_string($v['xml'], 'SimpleXMLElement', LIBXML_NOCDATA);
            $news = json_decode(json_encode($news), true);
            if(!empty($news['Articles']['item'][0])){
                $v['title'] = $news['Articles']['item'][$v['news_index']]['title'];
                $v['img'] = $news['Articles']['item'][$v['news_index']]['picUrl'];
            }else{
                $v['title'] = $news['Articles']['item']['title'];
                $v['img'] = $news['Articles']['item']['picUrl'];
            }
            unset($v['xml']);
            $newsArr[$k] = $v;
        }

        Output::instance()->objArray($newsArr, $total);
    }

    /**
     * 获取单条自媒体图文的评论总数
     * @param $mediaId /自媒体账号id
     */
    public function commentTotal($mediaId){
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $newIdx_table = M('news_comment_detail');
        Session::switchCustomer($cid);
        $commentTotal = $newIdx_table->where(['cid'=>$cid, 'mediaId'=>$mediaId,'deleted'=>0])->count();
        Output::instance()->object([
            'code'=>0,
            'data'=>[
                'commentTotal'=>$commentTotal
            ]
        ]);
    }

    /**
     * 获取单条图文的普通留言以及精选留言的总数
     * @param $newsIdx /图文索引的id
     * @return object
     */
    public function getNewsComtInfo($mediaId, $newsIdx){
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $newsInd_table = M('news_index_comment');
        Session::switchCustomer($cid);
        $material_table = M('material');

        $newsIdxInfo = $newsInd_table->alias('a')
            ->join('inner join wx_'.$cid.'_material b on a.materialId=b.id')
            ->field('a.*,b.xml')
            ->where(['a.id'=>$newsIdx])->find();
        if(!$newsIdxInfo){
            Output::instance()->object([
                'code'=>-1,
                'msg'=>'暂无图文'
            ]);
            return;
        }

        $news = simplexml_load_string($newsIdxInfo['xml'], 'SimpleXMLElement', LIBXML_NOCDATA);
        $news = json_decode(json_encode($news), true);

        $normal = self::newsCommentsType($mediaId, $newsIdx, 1, 0); //普通
        $elect = self::newsCommentsType($mediaId, $newsIdx, 1, 1);  //精选
        $data = [];
        $data['normalCount'] = $normal;
        $data['electCount'] = $elect;
        if(!empty($news['Articles']['item'][0])){
            $data['newsTitle'] = $news['Articles']['item'][$newsIdxInfo['news_index']]['title'];
        }else{
            $data['newsTitle'] = $news['Articles']['item']['title'];
        }

        if($data){
            Output::instance()->object([
                'code'=>0,
                'data'=>$data
            ]);
            return;
        }
        Output::instance()->resultCode(code_sql_error);

    }

    /**
     * 获取单个图文下的普通留言或者精选留言
     * @param $mediaId /自媒体id
     * @param $newsIdx /图文索引表中的id
     * @param $start /分页起始
     * @param $limit /分页大小
     * @param $order  /排序规则
     * @param $by     /排序字段
     * @param $type /0直接返回前端 1内部调用
     * @param $commentType /0普通留言 1精选留言
     * @return object|int
     */
    public function newsCommentsType($mediaId, $newsIdx, $type=0, $commentType = 0, $search='', $start=0, $limit=10, $order='desc', $by='comment_time'){
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        //按照评论时间倒序查,同时查询出用户的图像昵称
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $newsCom_table = M('news_comment_detail');
        Session::switchCustomer($cid);
        $material_table = M('material');

        $map = [];
        //$map['mediaId'] = $mediaId;
        $map['a.cid'] = $cid;
        $map['a.news_ind_id'] = $newsIdx;
        $map['a.comment_type'] = $commentType;
        $map['a.deleted'] = 0;
        if($search){
            $map['a.comment_content|u.nickname'] = [["like",'%'.$search.'%'],'or'];
            /*$map['a.comment_content|u.nickname'] = [["like",'%'.$search.'%'],'or'];*/
        }
        $commentList = $newsCom_table->alias('a')
            ->field('u.nickname, u.headimgurl, a.id, a.news_ind_id as newsIndId, a.comment_content as content, a.openid, a.user_comment_id as
            commentId, a.comment_time as commentTime, a.comment_type as commentType,a.comment_reply as commentReply,i.msg_data_id as msgDataId, i.news_index as idx, i.materialId')
            ->join('inner join wx_'.$cid.'_user_weixin_info u on a.openid=u.openid')
            ->join('inner join wx_news_index_comment i on a.news_ind_id=i.id and i.mediaId='.$mediaId)
            ->where($map)
            ->limit($start, $limit)
            ->order(['a.'.$by=>$order])
            ->select();

        $total = $newsCom_table->alias('a')
            ->field('u.nickname')
            ->join('inner join wx_'.$cid.'_user_weixin_info u on a.openid=u.openid')
            ->join('inner join wx_news_index_comment i on a.news_ind_id=i.id and i.mediaId='.$mediaId)
            ->where($map)
            ->count();
        if($type){
            return $total;
        }
        $newsComArr = [];
        foreach($commentList as $k=>$v){
            if($v['commentReply']){
                $v['commentReply'] = json_decode($v['commentReply'], true);
            }
            $newsComArr[$k] = $v;
        }
        Output::instance()->objArray($newsComArr, $total);
    }

    /**
     * (停用)开启已群发文章评论,和关闭评论接口整合到一起
     * @param $mediaId /自媒体id
     * @param $newsIndId /单条图文的id
     * @param $msgDataId /消息id
     * @param $idx       /图文索引
     * @return object
     */
    public function openComment($mediaId, $newsIndId, $msgDataId, $idx)
    {

        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $retArr = WxNewsComment::wxOpenComment($mediaId, $msgDataId, $idx);
        if($retArr['code'] < 0){
            Output::instance()->object($retArr);
            return;
        }

        /*更改本地是否开启评论字段*/
        $updateRet = self::isOpenComment($mediaId, 1, $newsIndId);
        if(!$updateRet){
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        Output::instance()->resultCode();
    }

    /**
     * 关闭或者开启群发文章的评论
     * @param $mediaId /自媒体id
     * @param $newsIndId /单条图文的id
     * @param $msgDataId /消息id
     * @param $idx       /图文索引
     * @param $setType   /开启还是关闭评论0:关闭, 1:开启
     * @return object
     */
    public function closeComment($mediaId, $newsIndId, $msgDataId, $idx, $setType=0)
    {
        $retVal = Session::init();
        $cid = Session::$user['customerId'];
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        M()->startTrans();
        if($setType == 0){
            /*更改本地是否开启评论字段*/
            $updateRet = self::isOpenComment($mediaId, $setType, $newsIndId,$cid);
            if($updateRet == false){
                M()->rollback();
                Output::instance()->resultCode(code_sql_error);
                return;
            }
            $retArr = WxNewsComment::wxCloseComment($mediaId, $msgDataId, $idx);
            if($retArr['code'] > 0){
                M()->rollback();
                Output::instance()->object($retArr);
                return;
            }
        }else{
            /*更改本地是否开启评论字段*/
            $updateRet = self::isOpenComment($mediaId, $setType, $newsIndId,$cid);
            if($updateRet == false){
                M()->rollback();
                Output::instance()->resultCode(code_sql_error);
                return;
            }
            $retArr = WxNewsComment::wxOpenComment($mediaId, $msgDataId, $idx);
            if($retArr['code'] > 0){
                M()->rollback();
                Output::instance()->object($retArr);
                return;
            }
        }
        M()->commit();
        Output::instance()->resultCode();
    }

    /**
     * 将评论标记精选或者取消精选
     * @param $msgDataId /消息id
     * @param $idx       /图文索引
     * @param $userCommentId       /用户评论id
     * @param $newsIndId       /图文id
     * @param $mediaId /自媒体id
     * @param $electType       /0:移出精选,1:移入精选
     * @param $commentDate /需要操作的留言数据 json
     * @return object
     */
    //public function markElectComment($mediaId, $msgDataId, $idx, $userCommentId, $electType,$newsIndId)
    public function markElectComment($mediaId, $commentDate,$electType)
    {
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $commentDate = json_decode($commentDate, true);
        M()->startTrans();
        foreach($commentDate as $k=>$v){
            if($electType == 0){
                $updateRet = self::updateLocalMarkElect($mediaId, 0, $electType, $v['commentId'],'',$v['newsIndId']);
                if($updateRet === false){
                    M()->rollback();
                    Output::instance()->resultCode(code_sql_error);
                    return;
                }
                $retArr = WxNewsComment::wxUnMarkElectComment($mediaId, $v['msgDataId'], $v['idx'],$v['commentId']);
                if($retArr['code'] > 0){
                    M()->rollback();
                    Output::instance()->object($retArr);
                    return;
                }

            }else{
                /*更改本地这条评论的comment_type状态为精选 */
                $updateRet = self::updateLocalMarkElect($mediaId, 0, $electType, $v['commentId'],'',$v['newsIndId']);
                if($updateRet === false){
                    M()->rollback();
                    Output::instance()->resultCode(code_sql_error);
                    return;
                }
                $retArr = WxNewsComment::wxMarkElectComment($mediaId, $v['msgDataId'], $v['idx'], $v['commentId']);
                if($retArr['code'] > 0){
                    M()->rollback();
                    Output::instance()->object($retArr);
                    return;
                }
            }
        }
        M()->commit();
        Output::instance()->resultCode();
    }

    /**
     * (暂不用)将评论取消精选,和移入精选接口整合一起
     * @param $mediaId /自媒体id
     * @param $msgDataId /消息id
     * @param $idx       /图文索引
     * @param $userCommentId       /用户评论id
     * @param $newsIndId       /图文id
     * @return object
     */
    public function unMarkElectComment($mediaId, $msgDataId, $idx, $userCommentId,$newsIndId)
    {
        /*5.将评论取消精选
	https://api.weixin.qq.com/cgi-bin/comment/unmarkelect?access_token=ACCESS_TOKEN
        */
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $retArr = WxNewsComment::wxUnMarkElectComment($mediaId, $msgDataId, $idx, $userCommentId);
        if($retArr['code'] > 0){
            Output::instance()->object($retArr);
            return;
        }

        $updateRet = self::updateLocalMarkElect($mediaId, 0, 0, $userCommentId,$newsIndId);
        if(!$updateRet){
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        Output::instance()->resultCode();
    }

    /**
     * 删除评论
     * @param $mediaId  /自媒体id
     * @param $msgDataId /消息id
     * @param $idx       /图文索引
     * @param $userCommentId  /用户评论id
     * @param $newsIndId  /图文id
     * @return object
     */
    public function delComment($mediaId, $msgDataId, $idx, $userCommentId,$newsIndId)
    {

        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        M()->startTrans();
        /*删除本地的这条评论*/
        $updateRet = self::updateLocalMarkElect($mediaId, 1, 1, $userCommentId,'',$newsIndId);
        if($updateRet == false){
            M()->rollback();
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $retArr = WxNewsComment::wxDelComment($mediaId, $msgDataId, $idx, $userCommentId);
        if($retArr['code'] > 0){
            M()->rollback();
            Output::instance()->object($retArr);
            return;
        }
        M()->commit();
        Output::instance()->resultCode();
    }

    /**
     * 回复评论
     * @param $mediaId /自媒体id
     * @param $msgDataId /消息id
     * @param $idx       /图文索引
     * @param $userCommentId       /用户评论id
     * @param $content      /回复内容
     * @param $newsIndId      /图文id
     * @return object
     */
    public function addReply($mediaId, $msgDataId, $idx, $userCommentId, $content='',$newsIndId)
    {

        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /*将本地的这条评论中加上回复内容*/
        M()->startTrans();
        $updateRet = self::updateLocalMarkElect($mediaId, 2, 0, $userCommentId, $content,$newsIndId);
        if(!$updateRet){
            M()->rollback();
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $retArr = WxNewsComment::wxAddReply($mediaId, $msgDataId, $idx, $userCommentId, $content);
        if($retArr['code'] > 0){
            M()->rollback();
            Output::instance()->object($retArr);
            return;
        }
        M()->commit();
        Output::instance()->resultCode();
    }

    /**
     * 删除回复
     * @param $mediaId /自媒体id
     * @param $msgDataId /消息id
     * @param $idx       /图文索引
     * @param $userCommentId       /用户评论id
     * @param $newsIndId       /用户评论id
     * @return object
     */
    public function delReply($mediaId, $msgDataId, $idx, $userCommentId,$newsIndId)
    {
        $retVal = Session::init();
        if(!$retVal){
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        /*将本地的这条评论中的回复删除*/
        M()->startTrans();
        $updateRet = self::updateLocalMarkElect($mediaId, 3, 0, $userCommentId,'', $newsIndId);
        if(!$updateRet){
            M()->rollback();
            Output::instance()->resultCode(code_access_denied);
            return;
        }

        $retArr = WxNewsComment::wxDelReply($mediaId, $msgDataId, $idx, $userCommentId);
        if($retArr['code'] > 0){
            M()->rollback();
            Output::instance()->object($retArr);
            return;
        }
        M()->commit();
        Output::instance()->resultCode();
    }

    /**
     * 更改本地的留言状态
     * @param $mediaId /自媒体id
     * @param $type     /0:精选1:删除2:回复评论3:删除回复,4:开启评论,5:关闭评论
     * @param $status /0取消精选,1精选 删除状态0:不删除,1:删除
     * @param $userCommentId /单条评论id
     * @param $content /回复评论的内容
     * @param $newsIndId /图文id
     * @return bool
     */
    protected function updateLocalMarkElect($mediaId, $type = 0, $status, $userCommentId=null, $content='',$newsIndId='')
    {
        Session::init();
        $cid = Session::$user['customerId'];
        Session::switchCustomer(0);
        $newsCom_table = M('news_comment_detail');
        Session::switchCustomer($cid);
        $commentRet = $newsCom_table->where(['cid'=>$cid,'news_ind_id'=>$newsIndId, 'user_comment_id'=>$userCommentId])->find();
        if($commentRet == null){
            var_dump($newsCom_table->getLastSql());
            return false;
        }
        /*$comment_detail = json_encode($commentRet['comment_detail'], true);*/
        $map = [];
        $map['id'] = $commentRet['id'];
        switch($type){
            case 0: //更改是否精选
                /*$comment_detail['comment_type'] = $status;
                $comment_detail = json_encode($comment_detail);*/
                $updateRet = $newsCom_table->where($map)->save(['comment_type'=>$status]);
                break;
            case 1: //删除评论
                $updateRet = $newsCom_table->where($map)->save(['deleted'=>$status]);
                break;
            case 2: //回复评论
                $comment_detail = [];
                $comment_detail['content'] = $content;
                $comment_detail['create_time'] = date('Y-m-d H:i:s');
                $comment_detail = json_encode($comment_detail,JSON_UNESCAPED_UNICODE);
                $updateRet = $newsCom_table->where($map)->save(['comment_reply'=>$comment_detail]);
                break;
            case 3: //删除回复
                /*$comment_detail = json_encode($comment_detail);*/
                $updateRet = $newsCom_table->where($map)->save(['comment_reply'=>'']);
                break;
            default:
                return false;
        }
        if($updateRet === false){
            var_dump($newsCom_table->getLastSql());
            return false;
        }
        return true;
    }

    /**
     * 更改本地留言评论开启状态
     * @param $mediaId /自媒体id
     * @param $status /0开启,1关闭
     * @param $newsIndId /单条图文id
     * @param $cid /customerId
     * @return bool
     */
    protected function isOpenComment($mediaId, $status, $newsIndId,$cid)
    {
        Session::switchCustomer(0);
        $newsInd_table = M('news_index_comment');
        Session::switchCustomer($cid);
        $newsIndRet = $newsInd_table->where(['cid'=>$cid,'id'=>$newsIndId])->find();
        if($newsIndRet == null){
            return false;
        }
        //$sql = 'UPDATE `wx_news_index_comment` SET `need_open_comment`="'.$status.'" WHERE ( `id` = "'.$newsIndRet['id'].'" )';
        $updateRet = $newsInd_table->where(['id'=>$newsIndRet['id']])->save([
            'need_open_comment'=>$status,
            'updateTime'=>date('Y-m-d H:i:s')
        ]);
        if($updateRet === false){
            return false;
        }
        return true;
    }

}

